from sqlmodel import Session, select
from app.models.user import User
from app.core.security import get_password_hash, verify_password

def get_user_by_email(session: Session, email: str) -> User | None:
    return session.exec(select(User).where(User.email == email)).first()

def create_user(session: Session, email: str, password: str, is_superuser: bool = False) -> User:
    user = User(email=email, hashed_password=get_password_hash(password), is_superuser=is_superuser)
    session.add(user)
    session.commit()
    session.refresh(user)
    return user

def authenticate_user(session: Session, email: str, password: str) -> User | None:
    user = get_user_by_email(session, email)
    if not user:
        return None
    if not verify_password(password, user.hashed_password):
        return None
    return user
